package com.sheng.project.test.zip;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author by ls
 * @date 2024/10/25
 */
public class ExcelZipExample {
    public static void main(String[] args) {
        String zipFileName = "excels.zip"; // 压缩包名称

        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName))) {
            for (int i = 1; i <= 5; i++) { // 假设生成5个Excel文件
                String excelFileName = "excel_" + i + ".xlsx";

                // 创建Excel工作簿
                Workbook workbook = new XSSFWorkbook();
                Sheet sheet = workbook.createSheet("Sheet1");

                // 在Excel中写入一些示例数据
                Row row = sheet.createRow(0);
                Cell cell = row.createCell(0);
                cell.setCellValue("Hello, Excel " + i);

                // 将Excel文件写入磁盘
                try (FileOutputStream fileOut = new FileOutputStream(excelFileName)) {
                    workbook.write(fileOut);
                }

                // 关闭工作簿
                workbook.close();

                // 添加Excel文件到压缩包
                ZipEntry zipEntry = new ZipEntry(excelFileName);
                zipOut.putNextEntry(zipEntry);
                zipOut.closeEntry();

                // 使用FileInputStream读取Excel文件内容并写入压缩包（可选）
                // You can also write the file contents directly to the zip if needed.
                // Here it is omitted for brevity.
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Excel files generated and zipped successfully.");
    }
}
